package logic

import (
	"context"
	"crypto/sha512"
	"fmt"
	"github.com/anaskhan96/go-password-encoder"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"user_srv/model"
	"user_srv/user_proto"
)

type Server struct {
	user_proto.UnimplementedUserServer
}

func (s *Server) UserRegister(ctx context.Context, in *user_proto.UserRegisterRequest) (*user_proto.UserInfo, error) {
	_, err := model.GetUserByMobile(in.Mobile)
	if err != nil {
		return nil, status.Error(codes.Internal, "用户已注册")
	}
	options := &password.Options{

		SaltLen:      10,
		Iterations:   10000,
		KeyLen:       50,
		HashFunction: sha512.New,
	}
	encode, s2 := password.Encode(in.Password, options)
	u := model.User{
		Mobile:   in.Mobile,
		Password: fmt.Sprintf("$pbkdf2-sha512$%s$%s", encode, s2),
		NickName: in.NickName,
	}
	register, _ := u.Register()
	if err != nil {
		return nil, status.Error(codes.Internal, "注册失败")
	}
	return &user_proto.UserInfo{
		Id:       int64(register.ID),
		Mobile:   register.Mobile,
		Password: register.Password,
		NickName: register.NickName,
		BirthDay: register.BirthDay,
		Sex:      int64(register.Sex),
		Age:      int64(register.Age),
	}, nil
}
